const db = require('../model')
const { Decrypt } = require('../utils/secret')
const Account = db.accounts
const Order = db.order

// crud  操作

// 查询一个用户操作,记录登录状态--session
exports.findOne = async (req, res) => {
	const { userId, secretPassword } = req.query
	const userPassword = Decrypt(secretPassword)
	const userData = await Account.findOne({
		where: { userId },
	})
	if (!userData) {
		return res.status(401).send({
			code: -1,
			message: '没有对应的用户',
		})
	}

	if (userData.userPassword !== userPassword) {
		return res.status(403).send({
			code: -1,
			message: '用户密码有错误',
		})
	}
	req.session.userId = userId
	const { count } = await Order.findAndCountAll({
		where: { userId, ordSituation: 0 },
	})

	return res.status(200).send({
		code: 1,
		count,
	})
}

// 查询用户详细信息
exports.findInfo = async (req, res) => {
	const { userId } = req.session
	const data = await Account.findOne({
		where: { userId },
	})
	return res.send({
		code: 1,
		data,
	})
}

// 新增用户操作
exports.create = async (req, res) => {
	const params = req.body
	const { userId } = params
	const userData = await Account.findOne({
		where: { userId },
		raw: true,
	})
	if (userData) {
		return res.send({
			code: -1,
			message: '已经存在对应的用户',
		})
	}
	await Account.create(params)

	return res.status(201).send({
		code: 1,
		message: '成功创建用户',
	})
}

// 更改用户基本信息(userId, userSex, userAge, userBirthday)
exports.update = async (req, res) => {
	const { userId } = req.session
	const data = await Account.update(req.body, { where: { userId } })
	if (data) {
		return res.send({
			code: 1,
		})
	}
}
